package com.dk.mq;

import com.dk.entity.Evaluate;
import com.dk.service.OrderServiceI;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.QueryAnnotation;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;

import javax.annotation.Resource;
import java.util.Objects;

@RocketMQTransactionListener(txProducerGroup = "tx-group")
public class MQClibackTransactionListener implements RocketMQLocalTransactionListener {

    @Resource
    private RedisTemplate redisTemplate;

    @Autowired
    private OrderServiceI orderServiceI;

//    消息的回调
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        //消费的头消息
        MessageHeaders headers = message.getHeaders();
        String messageId = message.getHeaders().getId().toString();
        //消费的具体内容, 这个是给消费者用的
        String string = new String((byte[]) message.getPayload());
        System.out.println(string);
        //提供者要用的数据
        Evaluate evaluate = (Evaluate) o;
        System.out.println("传递的实体类: " + evaluate);
        //根据orderNumber修改订单状态
        try {
//            增加评论 MongoDB
            orderServiceI.insertEvaluate(evaluate);
        }catch (Exception e){
            e.printStackTrace();
            //告诉mq不要提交,回滚
            redisTemplate.boundHashOps("messageId").put(messageId,"2");//2表示失败
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        //告诉mq消息提交
        redisTemplate.boundHashOps("messageId").put(messageId,"1");//1表示成功
        return RocketMQLocalTransactionState.COMMIT;
    }
//消息的回查
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String messageId = message.getHeaders().getId().toString();
        String stutas = (String) redisTemplate.boundHashOps("messageId").get(messageId);
        if (Objects.equals(stutas, "1")){
            return RocketMQLocalTransactionState.COMMIT;
        }else if (Objects.equals(stutas, "2")){
            return RocketMQLocalTransactionState.ROLLBACK;
        }else {
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }










}
